package com.gdkj.util;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.ame.v20190916.AmeClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class Utils {
    private Utils() {

    }

    private static AmeClient ameClient = null;

    public static AmeClient getAmeClient() {
        if (ameClient == null) {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDEEzTgcIhpsjLhohMltmPlqeCVZR6WhcI", "TgdM2bw1rSp10kFUUEk00lGUR8amhWEi");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ame.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            ameClient = new AmeClient(cred, "", clientProfile);
        }

        return ameClient;
    }

    /**
     * 获取推流或者拉流地址
     *
     * @param privateConfig
     * @param stream
     * @param type
     * @return java.lang.String
     */
    public static String getPushAndPullAddress(JSONObject privateConfig, String stream, Integer type) {
        String url;
        String bizId = privateConfig.getString("tx_bizid");
        String pushUrlKey = privateConfig.getString("tx_push_key");
        String push = privateConfig.getString("tx_push");
        String pull = privateConfig.getString("tx_pull");

        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeNew = localDateTime.plusDays(1);
        long timestampNew = localDateTimeNew.toEpochSecond(ZoneOffset.of("+8"));
        String txTime = Long.toHexString(timestampNew);

        String txSecret = SecureUtil.md5(pushUrlKey + stream + txTime);
        String safeUrl = String.format("&txSecret=%s&txTime=%s", txSecret, txTime);
        if (type == 1) {
            url = String.format("rtmp://%s/live/%s?bizid=%s%s", push, stream, bizId, safeUrl);
        } else {
            url = String.format("http://%s/live/%s.flv", pull, stream);
        }
        return url;
    }

    /**
     * 根据文件路径获取文件内容
     * @param fileName
     * @return java.lang.String
     * @throws IOException
     */
    public static String getFileContent(String fileName) throws IOException {
        ClassPathResource resource = new ClassPathResource(fileName);
        InputStream inputStream = resource.getInputStream();
        return IOUtils.toString(inputStream);
    }
}
